<template>
  <div>
	<ArtRuleSearchForm
		ref="visualProjectSearchFormRef"
		:rule="visualProjectSearchFormRule" 
		:showExpand="false"
		@reset="handleProjectReset"
		@search="handleProjectSearch"
	></ArtRuleSearchForm> 
	
	 <div shadow="never" class="custom-pane" style="height: calc(100vh - 224px);margin-top: 10px;">
		<div class="head" >
			<ElRow :gutter="20" style="width: 100%;padding-top: 0.5rem;padding-bottom: 0.5rem;">
			  <ElCol 
				:xs="24"
				:sm="12"
				:md="12"
				:lg="12"
				:xl="12"
			  >
			    <h4>项目列表</h4>
			  </ElCol>
			  <ElCol 
				:xs="24"
				:sm="12"
				:md="12"
				:lg="12"
				:xl="12"
				style="display: flex; justify-content: end"
			  >
			    <ElButton type="primary" :icon="Plus" @click="openDialog('add')" >新增项目</ElButton>
			  </ElCol>
			</ElRow>
		</div>
		<div class="body">
			<el-scrollbar height="calc(100vh - 330px)" >
				<div class="project-list">
					<div class="list">
					  <div class="offset">
					    <div class="item" v-for="item in tableData" :key="item.id" >
					      <!-- 骨架屏 -->
					      <ElSkeleton animated :loading="loading" style="width: 100%; height: 100%">
					        <template #template>
					          <div class="top">
					            <ElSkeletonItem
					              variant="image"
					              style="width: 100%; height: 100%; border-radius: 10px"
					            />
					            <div style="padding: 16px 0">
					              <ElSkeletonItem variant="p" style="width: 80%" />
					              <ElSkeletonItem variant="p" style="width: 40%; margin-top: 10px" />
					            </div>
					          </div>
					        </template>
					
					        <template #default>
					          <div class="top">
					            <ElImage class="cover" :src="item.home_img" lazy fit="cover">
					              <template #error>
					                <div class="image-slot">
					                  <ElIcon><icon-picture /></ElIcon>
					                </div>
					              </template>
					            </ElImage>
					
					            <span class="type">{{ item.name }}</span> 
					          </div>
					          <div class="bottom">
					           <!-- <h2>{{ item.name }}</h2> -->
					            <div class="info">
					              <div class="text">
					                <i class="iconfont-sys">&#xe6f7;</i>
					                <span>{{ useDateFormat(item.create_time, 'YYYY-MM-DD HH:mm:ss') }}</span>
					                <div class="line"></div>
 					                <i class="iconfont-sys" @click.stop="openDialog('edit',item)">&#xe705;</i>
									<!-- <i class="iconfont-sys" @click.stop="toEdit(item)">&#xe705;</i> -->
					              </div>
								  <ElButton size="small" @click.stop="toEdit(item)">设计</ElButton>
					            </div>
					          </div>
					        </template>
					      </ElSkeleton>
					    </div>
					  </div>
					</div>
					<div style="margin-top: 16vh" v-if="showEmpty">
					  <ElEmpty :description="`未找到相关数据 ${EmojiText[0]}`" />
					</div>
				</div>
			</el-scrollbar>
			
			<div style="padding-right: 8px;padding-top:5px;display: flex;justify-content: right;align-items: center;border-top: 1px solid var(--art-card-border);">
			  <el-pagination
			    v-model:current-page="pagination.currentPage"
			    v-model:page-size="pagination.pageSize"
			    :page-sizes="[20, 50, 100, 200]"
			    layout="total, sizes, prev, pager, next, jumper"
			    :total="pagination.total"
				:background="true"
			    @size-change="handleSizeChange"
			    @current-change="handleCurrentChange"
			  />
			</div>
			
			
		</div>
	</div>
	
	<!--工程基本信息编辑表单-->
	<ElDialog
		v-model="dialogVisible"
		:title="dialogType === 'add' ? '新建项目' : '编辑项目'"
		width="50%"
		align-center
		:close-on-click-modal="false"
		draggable
	>
		<ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px">
			<ElFormItem label="缩略图" prop="thumbnail">
				<div class="avatar-upload-wrapper">
				  <ElUpload
					class="avatar-uploader"
					ref="upload"
					:auto-upload="false"
					:show-file-list="false"
					:on-change="handleChange"
					:before-upload="beforeUpload"
					accept="image/*"
				  >
					<div v-if="imageUrl" class="avatar-img-box" @mouseenter="hovering=true" @mouseleave="hovering=false">
					  <img
						:src="imageUrl"
						class="avatar"
						width="120"
						height="120"
						@click="handlePreview"
					  >
					  <el-button
						v-if="hovering"
						class="avatar-remove-btn"
						type="danger"
						size="small"
						@click.stop="removeImage"
					  >移除</el-button>
					</div>
					<div v-else class="avatar-upload-placeholder">
					  <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
					  <div class="avatar-upload-text">上传图片</div>
					</div>
				  </ElUpload>
				</div>
			</ElFormItem>	
			<ElFormItem label="项目名称" prop="name">
			  <ElInput v-model="formData.name" />
			</ElFormItem>
			
			<ElFormItem label="项目描述" prop="description">
			  <ElInput v-model="formData.description" type="textarea" :rows="3" />
			</ElFormItem>
			
		</ElForm>

		<template #footer>
			<div class="dialog-footer">
				<ElButton @click="dialogVisible = false">取消</ElButton>
				<ElButton type="primary" @click="handleSubmit">提交</ElButton>
			</div>
		</template>
	</ElDialog>
	
  </div>
</template>

<script setup lang="ts">
import { Picture as IconPicture } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, ScrollbarDirection } from 'element-plus'
import {
Plus
} from '@element-plus/icons-vue'
import { ref, onMounted, computed } from 'vue'
import { router } from '@/router'
import { useDateFormat } from '@vueuse/core'
import { Search } from '@element-plus/icons-vue'
import EmojiText from '@/utils/ui/emojo'
import { ArticleList } from '@/mock/temp/articleList'
import { useCommon } from '@/composables/useCommon'
import { RoutesAlias } from '@/router/routesAlias'
import ArtRuleSearchForm from '@/components/custom/forms/ArtRuleSearchForm.vue'
import { ElMessage } from 'element-plus'
import { ProjectService } from '@/api/visual/projectApi'
import { reactive } from 'vue-demi'
import { axiosInstance } from '@/utils/http/index'
import { objectToFormData } from '@/utils/form/form'

defineOptions({ name: 'visualProject' })

const visualProjectSearchFormRef=ref();
const visualProjectSearchFormRule=ref<string>('visual-project-search-form');
const formFilters = reactive({})
const visualProjectFormRef=ref();
const visualProjectFormRule=ref<string>('visual-project-form');
const dialogType = ref('add')
const dialogVisible = ref(false)
const loading = ref(false)
const _data=ref<any>({});
const openDialog = async (type: string, row?: any) => {
	dialogVisible.value = true
	dialogType.value = type
	if(visualProjectFormRef.value){
		visualProjectFormRef.value.resetForm()
	}
	
	if (type === 'edit' && row) {
	  Object.assign(formData, row)
	  imageUrl.value = row.thumbnail || ''
	} else {
	  Object.assign(formData, { id: '', name: '',description: '', thumbnail:'' ,thumbnailFile: null })
	  imageUrl.value = ''
	}
	
}

const handleChange = (file: any) => {
  formData.thumbnailFile = file.raw;
};

const removeImage = () => {
  formData.thumbnailFile = null;
  formData.thumbnail = '';
};

const MAX_SIZE_MB = 1;
const beforeUpload = (file: File) => {
  const isLt1M = file.size / 1024 / 1024 < MAX_SIZE_MB;
  if (!isLt1M) {
    ElMessage.error('图片大小不能超过1MB！');
  }
  return isLt1M;
};

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true
      try {
        const formDataToSend = objectToFormData(toRaw(formData));
        await ProjectService.save(formDataToSend)
        const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
        ElMessage.success(message)
        reloadProjectList();
      } catch {
        ElMessage.error(`失败`)
      } finally {
        dialogVisible.value = false
        loading.value = false
      }
    }
  })
}


const handleProjectSearch=()=>{
	pagination.currentPage = 1
	getProjectList()
}
const handleProjectReset=()=>{
	pagination.currentPage = 1
	getProjectList()
}
  

const  reloadProjectList=()=>{
	getProjectList()
}

const pagination = reactive({
	currentPage: 1,
	pageSize: 20,
	total:0
})

// 处理表格分页变化
const handleSizeChange = (newPageSize: number) => {
	pagination.pageSize = newPageSize
	getProjectList()
}

const handleCurrentChange = (newCurrentPage: number) => {
	pagination.currentPage = newCurrentPage
	getProjectList()
}

const tableData = ref<any[]>([])
const getProjectList = async () => {
	loading.value = true
	try {
	  Object.assign(formFilters, { ...visualProjectSearchFormRef.value.getFormData() })
	  const { list, pageNumber, pageSize, totalRow } = await ProjectService.pages({
		pageNumber: pagination.currentPage,
		pageSize:pagination.pageSize,
		query:formFilters
	  })
	  tableData.value = list;
	  Object.assign(pagination, { 
			currentPage: pageNumber,
			pageSize: pageSize, 
			total:totalRow
	  })
	} catch (error) {
	  console.error('获取列表失败:', error)
	} finally {
	  loading.value = false
	}
}

const formRef = ref<FormInstance>()
const formData = reactive({
  id: '',
  name: '',
  description: '',
  thumbnail: '',
  thumbnailFile: null,
});

const BASE_API = axiosInstance.defaults.baseURL
const hovering = ref(false);
const imageUrl = ref('')
// const imageUrl = computed(() =>
//   formData.thumbnailFile
//     ? URL.createObjectURL(formData.thumbnailFile)
//     : (formData.thumbnail
//         ? `${BASE_API}/visual/component/library/cover/${formData.thumbnail}?${new Date().getTime()}`
//         : '')
// );

// 表单验证规则
const rules = reactive<FormRules>({
	name: [
		{ required: true, message: '请输入项目名称', trigger: 'blur' },
		{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
	description: [{ min: 0, max: 250, message: '最大长度250 个字符', trigger: 'blur' }]
})

const handlePreview = () => {
  if (imageUrl.value) {
    window.open(imageUrl.value, '_blank');
  }
};

const showEmpty = computed(() => {
	return tableData.value.length === 0 && !loading.value
})

const toEdit = (item: any) => {
    router.push({
      path: '/visual-app/project-edit',
      query: {
        id: item.id
      }
    })
}

onMounted(() => {
	getProjectList()
})
</script>

<style lang="scss" scoped>

  .custom-pane{
  	border: 1px solid var(--art-card-border);
	padding: 20px 20px 0;
	background-color: var(--art-main-bg-color);
	border-radius: calc(var(--custom-radius) / 2 + 2px);
  	.head{
  		border-bottom: 1px solid var(--art-card-border);
  		display: flex;display: flex;
  		justify-content: flex-start;
  		align-items: center;
  		padding-left: 0.5rem;
  	}
  	.body{
  		padding: 0rem;
  	}
  	
  }
	
.avatar-upload-wrapper {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    min-height: 140px;
  }
  .avatar-uploader {
    width: 130px;
    height: 130px;
    border-radius: 12px;
    box-shadow: 0 2px 16px #1e90ff22;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    transition: box-shadow 0.3s, border 0.3s;
    border: 2px dashed #409eff88;
    overflow: hidden;
  }
  .avatar-uploader:hover {
    box-shadow: 0 6px 32px #409eff55;
    border: 2px solid #409eff;
  }
  .avatar-upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #8fa1c7;
    font-size: 16px;
    background: transparent;
    transition: background 0.2s;
  }
  .avatar-uploader-icon {
    font-size: 48px !important;
    color: #409effcc;
    margin-bottom: 8px;
    transition: color 0.2s;
  }
  .avatar-upload-text {
    font-size: 13px;
    color: #bfc6d1;
    letter-spacing: 1px;
  }
  .avatar-img-box {
    width: 100%;
    height: 100%;
    // border-radius: 12px;
    overflow: hidden;
    position: relative;
    box-shadow: 0 2px 16px #409eff33;
    // background: #181c24;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 2px;
  }
  .avatar-img-box img.avatar {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  .avatar-img-box:hover img.avatar {
    box-shadow: 0 6px 24px #409eff55;
  }
  .avatar-remove-btn {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%) scale(0.95);
    opacity: 0;
    transition: opacity 0.2s, transform 0.2s;
    z-index: 2;
    padding: 2px 18px;
    font-size: 14px;
    border-radius: 16px;
    background: rgba(255, 0, 0, 0.8);
    border: none;
  }
  .avatar-img-box:hover .avatar-remove-btn {
    opacity: 1;
    transform: translateX(-50%) scale(1.08);
  }
	
	
  .project-list {
	  width: 100%;
    .custom-segmented .el-segmented {
      height: 40px;
      padding: 6px;
      --el-border-radius-base: 8px;
    }

    .list {
      margin-top: 20px;

      .offset {
        display: flex;
        flex-wrap: wrap;
        // width: calc(100% + 20px);
        .item {
          box-sizing: border-box;
          width: calc(20% - 20px);
          margin: 0 20px 20px 0;
          cursor: pointer;
          border: 1px solid var(--art-border-color);
          border-radius: calc(var(--custom-radius) / 2 + 2px) !important;

          &:hover {
            .el-button {
              opacity: 1 !important;
            }
          }

          .top {
            position: relative;
            aspect-ratio: 16/9.5;

            .cover {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 100%;
              object-fit: cover;
              background: var(--art-gray-200);
              border-radius: calc(var(--custom-radius) / 2 + 2px)
                calc(var(--custom-radius) / 2 + 2px) 0 0;

              .image-slot {
                font-size: 26px;
                color: var(--art-gray-400);
              }
            }

            .type {
              position: absolute;
              top: 5px;
              right: 5px;
              padding: 5px 4px;
              font-size: 12px;
              color: rgba(#fff, 0.8);
              background: rgba($color: #000, $alpha: 60%);
              border-radius: 4px;
            }
          }

          .bottom {
            padding: 5px 10px;

            h2 {
              font-size: 16px;
              font-weight: 500;
              color: #333;

              @include ellipsis();
            }

            .info {
              display: flex;
              justify-content: space-between;
              width: 100%;
              height: 25px;
              margin-top: 6px;
              line-height: 25px;

              .text {
                display: flex;
                align-items: center;
                color: var(--art-text-gray-600);
				/* 添加以下样式实现省略号效果 */
				// max-width: 120px; /* 根据实际需要调整 */
				// white-space: nowrap; /* 禁止换行 */
				// overflow: hidden; /* 隐藏溢出内容 */
				// text-overflow: ellipsis; /* 显示省略号 */

                i {
                  margin-right: 5px;
                  font-size: 14px;
                }

                span {
                  font-size: 13px;
                  color: var(--art-gray-600);
                }

                .line {
                  width: 1px;
                  height: 12px;
                  margin: 0 15px;
                  background-color: var(--art-border-dashed-color);
                }
              }

              // .el-button {
              //   opacity: 0;
              //   transition: all 0.3s;
              // }
            }
          }
        }
      }
    }
  }

  // @media only screen and (max-width: $device-notebook) {
  //   .project-list {
  //     .list {
  //       .offset {
  //         .item {
  //           width: calc(25% - 20px);
  //         }
  //       }
  //     }
  //   }
  // }

  // @media only screen and (max-width: $device-ipad-pro) {
  //   .project-list {
  //     .list {
  //       .offset {
  //         .item {
  //           width: calc(33.333% - 20px);

  //           .bottom {
  //             h2 {
  //               font-size: 16px;
  //             }
  //           }
  //         }
  //       }
  //     }
  //   }
  // }

  // @media only screen and (max-width: $device-ipad) {
  //   .project-list {
  //     .list {
  //       .offset {
  //         .item {
  //           width: calc(50% - 20px);
  //         }
  //       }
  //     }
  //   }
  // }

  // @media only screen and (max-width: $device-phone) {
  //   .project-list {
  //     .list {
  //       .offset {
  //         .item {
  //           width: calc(100% - 20px);
  //         }
  //       }
  //     }
  //   }
  // }
</style>
